package com.joshondesign.sdljava.gfx;

import com.joshondesign.sdljava.SDL;
import com.joshondesign.sdljava.SDLConstants;
import com.joshondesign.sdljava.SDL_PixelFormat;
import com.joshondesign.sdljava.SDL_Surface;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: josh
 * Date: 9/11/11
 * Time: 4:49 PM
 * To change this template use File | Settings | File Templates.
 */
public class VerticalLinearGradient extends LinearGradient {
    private int start;
    private int end;
    private List<Double> values = new ArrayList<Double>();
    private List<SColor> colors = new ArrayList<SColor>();
    private SDL_Surface _texture;

    public VerticalLinearGradient(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public VerticalLinearGradient addColor(double value, SColor color) {
        this.values.add(value);
        this.colors.add(color);
        return this;
    }

    public SDL_Surface getImage(SDL_Surface surface) {
        if(_texture == null) {
            double length = this.end-this.start;
            SDL_PixelFormat format = surface.getFormat();
            SDL_Surface surface2 = SDL.SDL_CreateRGBSurface(SDLConstants.SDL_SWSURFACE,
                    1, (int)length,
                    format.getBitsPerPixel(), format.getRmask(), format.getGmask(), format.getBmask(), format.getAmask());
            format.delete();

            double v = values.get(0);
            SColor c = colors.get(0);
            int currentIndex = 0;
            //for each span
            for(int i=1; i<values.size(); i++) {
                double nv = values.get(i);
                SColor nc = colors.get(i);
                double spanFract = nv-v;
                int spanLength = (int) (length*spanFract);

                for(int j=0; j<spanLength; j++) {
                    double colorFraction = ((double)j)/spanLength;
                    SColor finalColor = SColor.interpolate(c,nc,colorFraction);
                    SDL.setPixel(surface2,0,currentIndex+j,finalColor._sdlcolor);
                }
                currentIndex += spanLength;

                v = nv;
                c = nc;
            }
            _texture = surface2;
        }
        return _texture;
    }
}
